package com.ruge._05_springboot_web.config.async;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

@Component
@Async  // 如果注解到方法上实现该方法的异步调用  如果注解到类上实现该类下的所有方法的异步调用
public class AsyncTask {

    public Future<String> task1() throws Exception {
        Long begin = System.currentTimeMillis();
        System.out.println("任务1 开始 ");
        Thread.sleep((long) (Math.random() * 1000));
        Long end = System.currentTimeMillis();
        System.out.println("任务1 结束 ");
        System.out.println("任务1总耗时=" + (end - begin));
        return new AsyncResult<String>("任务1总耗时=" + (end - begin));
    }

    public Future<String> task2() throws Exception {
        System.out.println("任务2 开始 ");
        Long begin = System.currentTimeMillis();
        Thread.sleep((long) (Math.random() * 1000));
        Long end = System.currentTimeMillis();
        System.out.println("任务2 结束 ");
        System.out.println("任务2总耗时=" + (end - begin));
        return new AsyncResult<String>("任务2总耗时=" + (end - begin));
    }

    public Future<String> task3() throws Exception {
        System.out.println("任务3 开始 ");
        Long begin = System.currentTimeMillis();
        Thread.sleep((long) (Math.random() * 1000));
        Long end = System.currentTimeMillis();
        System.out.println("任务3 结束 ");
        System.out.println("任务3总耗时=" + (end - begin));
        return new AsyncResult<String>("任务3总耗时=" + (end - begin));
    }
}
